package com.gwz.wxtime.core.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gwz.wxtime.chessboard.entity.chat.InputTextDTO;
import com.gwz.wxtime.chessboard.entity.chat.PerceptionDTO;
import com.gwz.wxtime.chessboard.entity.chat.TuLingRequest;
import com.gwz.wxtime.chessboard.entity.chat.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TuLingUtil {
    private static final String key = "b811ae91687f46b0a8ea946b5420c08d";

    public static String sendMessage(String wxId, String content) {
        TuLingRequest tuLingRequest = new TuLingRequest();
        tuLingRequest.setReqType(0);
        PerceptionDTO perceptionDTO = new PerceptionDTO();
        InputTextDTO inputTextDTO = new InputTextDTO();
        inputTextDTO.setText(content);
        perceptionDTO.setInputText(inputTextDTO);
        tuLingRequest.setPerception(perceptionDTO);
        tuLingRequest.setUserInfo(userInfo(wxId));

        log.info("图灵机器人请求:{}", JSON.toJSONString(tuLingRequest));
        String resultStr = HttpUtil.post("http://openapi.turingapi.com/openapi/api/v2", JSON.toJSONString(tuLingRequest));
        log.info("图灵机器人响应:{}", resultStr);
        JSONObject jsonObject = JSON.parseObject(resultStr);
        String string = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("values").getString("text");
        return string;
    }

    private static UserInfoDTO userInfo(String wxId) {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUserId(wxId);
        userInfoDTO.setApiKey(key);
        return userInfoDTO;
    }
}
